function getQueryString(name){
    var result = location.search.match(new RegExp('[\?\&]' + name+ '=([^\&]+)','i'));
    if(result == null || result.length < 1){
        return '';
    }
    return result[1];
};

function setCookie(name,value,days){
    var Days = days ? days : 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

Date.prototype.format = function(format) {
    var date = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        'h+': this.getHours(),
        'm+': this.getMinutes(),
        's+': this.getSeconds(),
        'q+': Math.floor((this.getMonth() + 3) / 3),
        'S+': this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ('00' + date[k]).substr(('' + date[k]).length));
        }
    }
    return format;
}

function goTop(acceleration, time) { 
    acceleration = acceleration || 0.1; 
    time = time || 16; 
     
    var x1 = 0; 
    var y1 = 0; 
    var x2 = 0; 
    var y2 = 0; 
    var x3 = 0; 
    var y3 = 0; 
     
    if (document.documentElement) { 
    x1 = document.documentElement.scrollLeft || 0; 
    y1 = document.documentElement.scrollTop || 0; 
    } 
    if (document.body) { 
    x2 = document.body.scrollLeft || 0; 
    y2 = document.body.scrollTop || 0; 
    } 
    var x3 = window.scrollX || 0; 
    var y3 = window.scrollY || 0; 
     
    // 滚动条到页面顶部的水平距离 
    var x = Math.max(x1, Math.max(x2, x3)); 
    // 滚动条到页面顶部的垂直距离 
    var y = Math.max(y1, Math.max(y2, y3)); 
     
    // 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小 
    var speed = 1 + acceleration; 
    window.scrollTo(Math.floor(x / speed), Math.floor(y / speed)); 
     
    // 如果距离不为零, 继续调用迭代本函数 
    if(x > 0 || y > 0) { 
    var invokeFunction = "goTop(" + acceleration + ", " + time + ")"; 
    window.setTimeout(invokeFunction, time); 
    } 
} 
$(function(){
    $("form").validate({
        errorPlacement: function(error, element) {  
            if (element.attr("name") == "check")   
                error.insertAfter(".btn-send-code");
            else    
                error.insertAfter(element); 
        },
        success:function(label) {
            if(label.attr('id')=='phone-error'){
                $('.i4 span').addClass('active');
            }
        },
        submitHandler: function(form) {
            //form.submit();
            // $(form).ajaxSubmit();
        }
    });




    var time = 60;
    $('.btn-send-code').on('click',function(){
        if(!$(this).hasClass('active')) return;
        if(time == 60){
            if($('#phone').val()!=""){
                var count = setInterval(function(){
                    if(time<=1){
                        $('.btn-send-code').text('获取验证码');
                    }else{
                        $('.btn-send-code').text(time-=1);
                    }
                },1000);
            }else{
                showtoastFromDocumentCods();
                return false;
            }
        }
    });

    function showtoastFromDocumentCods(){
        showMessage('请输入有效验证码！',3000,true,'bounceInUp-hastrans','bounceOutDown-hastrans');
    }
    //function showtoastFromDocumentCod(){
    //    showMessage('验证码已发送，请耐心等待！',3000,true,'bounceInUp-hastrans','bounceOutDown-hastrans');
    //}


})
$('.go-top').on('click',function(){
    goTop();
});
$('.clear-btn').on('click',function(){
    $('#account').val('');
});

$(function(){
    if($('.page-pay').length > 0){
        $('.money').text('￥'+$('#danjia').val());

        $('.add').on('click',function(){
            var month= parseInt($('.g3 .num').text());
            if(month<10000){
                $('.g3 .num').text( month+1 );
            }
            
            checkMinMonth();
        });
        $('.remove').on('click',function(){
            var month = parseInt($('.g3 .num').text());
            if(month>1){
                $('.g3 .num').text( month-1 );
            }
            checkMinMonth();
        });

        function checkMinMonth(){
            var month = parseInt($('#month-size').text());
            if(month!=1){
                $('.g3 .remove img').attr('src','/static/img/img-25-1.png');
            }else{
                $('.g3 .remove img').attr('src','/static/img/img-25.png');
            }

            $('.money').text('￥'+(month*$('#danjia').val()));
        }

        $('.use-offer').on('click',function(){
            if($(this).hasClass('active')){
                $(this).removeClass('active').attr('src','/static/img/img-26-1.jpg');
                $(this).parent().find('p').removeClass('active');
            }else{
                $(this).addClass('active').attr('src','/static/img/img-26.png');
                $(this).parent().find('p').addClass('active');
            }
        });


        $('.check-btn').on('click',function(){
            var code = $('#offer-code').val();
            if(code==''){
                return;
            }
            $.ajax({
                url:'/check/coupon',          //   检测优惠券是否能够使用
                type:'get',
                data:{
                    code: code
                },
                timeout:5000,
                dataType:'json',
                success:function(data,textStatus,jqXHR){
                    if(data.error_code==0){
                        if(data.data.status==true){
                            alert('优惠码可使用！付款时自动减免金额！');
                        }
                    }else{
                        layer.msg(data.error_message);
                    }
                },
                error:function(xhr,textStatus){
                    alert('失败！');
                }
            })
        });

        $('.pay-now').on('click',function(){
            //var account = $('#account').val();
            var month = $('#month-size').text();
            var code = $('#offer-code').val();
            var product = $('#product').val();
            if(month==''){
                layer.msg('请输入完整信息');
                return;
            }
            window.location.href ='/createOrder?month='+month+'&code='+code+'&product='+product;
        });
    }
});
$('.btn-copy').on('click',function(){
    var text = $('.copy-link').eq(0);
    text.select();
    document.execCommand("Copy");
    alert('已复制');
});
var layer = layui.layer;


$('.btn-bind-phone').on('click',function(){
    var phone = $('#phone').val();
    var pattern = /^[1][0-9]{10}$/;
    if(!pattern.test(phone)){
        layer.msg('请输入正确手机号');
        return;
    }

    $.ajax({
        url:'/bind/phone',
        type:'get',
        data:{
            phone: phone
        },
        timeout:5000,
        dataType:'json',
        success:function(data,textStatus,jqXHR){
            if(data.error_code==0){
                alert('请从新登录');
                window.location.href = '/user';
            }else{
                layer.msg(data.error_message);
            }
        },
        error:function(xhr,textStatus){
            alert('失败！');
        }
    })
});

$('.btn-bind-email').on('click',function(){
    var email = $('#email').val();
    var pattern = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    if(!pattern.test(email)){
        layer.msg('请输入正确邮箱');
        return;
    }

    $.ajax({
        url:'/bind/email',
        type:'get',
        data:{
            email: email
        },
        timeout:5000,
        dataType:'json',
        success:function(data,textStatus,jqXHR){
            if(data.error_code==0){
                window.location.href = '/user';
            }else{
                layer.msg(data.error_message);
            }
        },
        error:function(xhr,textStatus){
            alert('失败！');
        }
    })
});

$('.btn-bind-qq').on('click',function(){
    var qq = $('#qq').val();
    //var pattern = /^\d{6,11}$/;
    //if(!pattern.test(email)){
    //    layer.msg('请输入正确QQ号');
    //    return;
    //}

    $.ajax({
        url:'/bind/qq',
        type:'get',
        data:{
            qq: qq
        },
        timeout:5000,
        dataType:'json',
        success:function(data,textStatus,jqXHR){
            if(data.error_code==0){
                window.location.href = '/user';
            }else{
                layer.msg(data.error_message);
            }
        },
        error:function(xhr,textStatus){
            alert('失败！');
        }
    })

});

$('.btn-bind-pass').on('click',function(){
    var pass = $('#pass').val();
    var confirm = $('#confirm').val();
    var pattern = /^[0-9a-z]{0,10}$/;
    if(!pattern.test(pass)){
        layer.msg('请输入0-10数字，母');
        return;
    }

    $.ajax({
        url:'/update/password',
        type:'get',
        data:{
            password: pass,
            new_password: confirm,

        },
        timeout:5000,
        dataType:'json',
        success:function(data,textStatus,jqXHR){
            if(data.error_code==0){
                alert('请从新登录');
                    window.location.href = '/logout';
            }else{
                layer.msg(data.error_message);
            }
        },
        error:function(xhr,textStatus){
            alert('失败！');
        }
    })


});
